/**
 * @title 高级表格的基础应用(基本示例1)
 * @description 多选、合计、分页、列拖拽、列过滤
 *
 */
import React, { Component } from "react";

import Modal from 'bee-modal';
import 'bee-modal/build/Modal.css';

import { Button, Icon } from "tinper-bee";

import Table from "bee-table";
import 'bee-table/build/Table.css';
import Checkbox from 'bee-checkbox';
import { vendorsSetStorage, vendorsGetStorage, vendorsDanger, vendorsFmtDate, vendorsGetUrlParam } from 'utils/config.js';
import axios from 'axios';
import './index.less'

class ReferSingleSelect extends Component {
    constructor(props) {
        super(props);
        let _self = this;
        this.state = {
            item: {},
            columns: [],
            selectedList: [],
            showModal: false,
            data: []
        }
    }

    onCheckBoxChange = (e, text, record, index) => {
        console.log(record)
        let { data, } = this.state;
        let selectedList = [];
        data.map((item, dataIndex) => {
            if (dataIndex === index) {
                item._checked = e;

            }
            if(item._checked){
                selectedList.push(item);
            }
        })
        this.setState({
            data,
            selectedList
        }, () => {
            console.log(selectedList)
        })
    }
    close = () => {
        this.setState({
            showModal: false
        }, () => {
            // let { item: { refPk }, data, selectedList } = this.state;
            // let showValue = this.getShowValue()
            // this.props.upDataValues(refPk, showValue)
        })
    }

    showGrid = ({ item, index, dataSource, reqData }) => {
        let { reqRef, refPk } = item;
        let newcolumns = this.setColumns(item)
        let cacheData = vendorsGetStorage(dataSource)

        if (cacheData && cacheData[refPk] && cacheData[refPk]['refData'].length && (
            (typeof cacheData[refPk]['reqData'] === 'string' && cacheData[refPk]['reqData'] == reqData) ||
            JSON.stringify(cacheData[refPk]['reqData']) === JSON.stringify(reqData)
        )) {

            // if ((
            //     typeof cacheData[refPk]['reqData'] === 'string' && cacheData[refPk]['reqData'] == reqData) ||
            //     JSON.stringify(cacheData[refPk]['reqData']) === JSON.stringify(reqData)
            // ) {
            this.setState({
                showModal: true,
                dataSource,
                item,
                data: cacheData[item.refPk]['refData'],
                selectedList: cacheData[item.refPk]['selectedList'],
                columns: newcolumns
            })
            return
            // }
        }
        this.updataRefData({ item, index, dataSource, reqData })
    }
    setColumns = (item) => {
        let _self = this;
        let { reqRef } = item;
        let newcolumns = [{
            title: '', dataIndex: "_checked", key: "_checked", width: '40px',
            render(text, record, index) {
                let _checked = text ? true : false
                return <Checkbox
                    onChange={(e) => { _self.onCheckBoxChange(e, text, record, index) }}
                    checked={_checked}
                />
            }
        }]
        //动态设置显示列
        reqRef.setCoByKey.forEach((item, index) => {
            newcolumns.push({ title: item.name, dataIndex: item.key, key: item.key })
        })
        return newcolumns
    }
    updataRefData = ({ item, index, dataSource, reqData }) => {
        let { reqRef } = item;
        let newcolumns = this.setColumns(item)
        this.setState({
            showModal: true,
            dataSource,
            item,
            data: [],
            selectedList: [],
            columns: newcolumns
        }, () => {
            let dataKey = reqRef.method === "get" ? "params" : 'data'
            !this.props.loading.getLoadingState() && this.props.loading.setLoadingState(true)
            axios({
                method: reqRef.method,
                url: reqRef.refUrl,
                [dataKey]: reqData,
                headers: {
                    'Cache-Control': 'no-cache',
                }
            }).then((res) => {
                this.props.loading.setLoadingState(false)
                let data = res.data;
                // asdhashd
                let tableData = []
                if (reqRef.setData) {
                    tableData = reqRef.setData(res)
                } else {
                    tableData = data.result
                }
                if (data.resultCode === 'ok') {
                    this.setState({
                        data: tableData,
                    }, () => {
                        let { data, selectedList, item: { refPk } } = this.state;
                        let showValue = this.getShowValue()
                        this.props.upDataValues(refPk, showValue)
                        this.updataRefcache({ data, selectedList, reqData });
                    })
                } else {
                    vendorsDanger({ 'text': data.exMsg })
                }
            })
        })
    }
    getSelectedDataFunc = (selectedList, record, index, newData) => {

    };

    updataRefcache = ({ data, selectedList, reqData }) => {
        let { dataSource, item: { refPk, selectShowKey } } = this.state;
        let cacheData = vendorsGetStorage(dataSource)
        console.log(cacheData)
        if (!cacheData[refPk]) {
            cacheData[refPk] = {}
        }
        cacheData[refPk]['refData'] = data
        cacheData[refPk]['selectedList'] = selectedList
        if (reqData) {
            cacheData[refPk]['reqData'] = reqData
        }
        vendorsSetStorage(dataSource, cacheData)
    }

    getShowValue = () => {
        let { selectedList, item: { refPk, selectShowKey } } = this.state;
        let value = ''
        selectedList.map((item, index) => {
            if (selectedList.length - 1 === index) {
                value += `${item[selectShowKey]}`
            } else {
                value += `${item[selectShowKey]},`
            }
        })
        return value
    }


    sureClick = () => {
        let { item: { refPk }, data, selectedList } = this.state;
        this.updataRefcache({ data, selectedList });
        let showValue = this.getShowValue()
        this.setState({
            showModal: false,
        }, () => {
            this.props.upDataValues(refPk, showValue)
        })
    }

    render() {

        return (
            <div>
                <Modal show={this.state.showModal} size={'lg'} onHide={this.close} backdrop={false}>
                    <Modal.Header closeButton>
                        <Modal.Title > {this.state.item.label} </Modal.Title>
                    </Modal.Header >
                    <Modal.Body>

                        <Table
                            className='MultiSelectTable'
                            columns={this.state.columns}
                            data={this.state.data}
                            emptyText={() => '暂无数据'}
                            rowKey={this.setRowKey}
                            scroll={{ y: 380 }}
                            bordered
                        />

                    </Modal.Body>
                    <Modal.Footer>
                        <div className="refer-btn-group">
                            <Button className='icon-cancel-btn' onClick={this.close}> 取消 </Button>
                            <Button colors="primary" onClick={this.sureClick}> 确认 </Button>
                        </div>
                    </Modal.Footer>
                </Modal>
            </div >
        );
    }
}
export default ReferSingleSelect;